<template>
  <div class="container">
    <div class="forwarding-set" v-loading.body="listLoading">
      <!--搜索 -->
      <div class="title">
        <div class="search">
          <el-input placeholder="검색어를입력하세요" v-model="listQuery.keywords" class="input-with-select">
            <el-select v-model="listQuery.type" slot="prepend" placeholder="선택하세요">
              <el-option label="이메일" value="email"></el-option>
              <el-option label="닉네임" value="nickname"></el-option>
              <el-option label="역할" value="role"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
          </el-input>
        </div>
        <div class="button-group">
          <button @click="addpopup = true"><i class="fa fa-plus-circle"></i>추가</button>
        </div>
      </div>
      <!-- 批量操作 -->
      <div :class="unChecked?'artivle-batch-bar hide':'artivle-batch-bar'">
        <el-checkbox class="check-all" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"></el-checkbox>
        <el-button :loading="false" size="mini" class="batch-btn" @click="handleDelete(checked)" :disabled="unChecked">
          <i class="fa fa-trash-o"></i>삭제</el-button>
      </div>
      <!-- 列表 -->
      <el-table :data="list" style="width: 100%" class="bd">

        <el-table-column width="40px">
          <template slot-scope="scope">
            <el-checkbox-group v-model="checked">
              <el-checkbox :label="scope.row.id " style="padding-left: 7px;"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>

        <el-table-column width="150px" align="center" show-overflow-tooltip label="프로필">
          <template slot-scope="scope">
            <img class="user-avatar" :src="scope.row.avatar===null?'../static/user/user-avatar-default.png':scope.row.avatar">
          </template>
        </el-table-column>

        <el-table-column width="150px" align="left" show-overflow-tooltip label="닉네임">
          <template slot-scope="scope">
            {{ scope.row.nickname }}
          </template>
        </el-table-column>

        <el-table-column align="left" show-overflow-tooltip label="이메일">
          <template slot-scope="scope">
            {{ scope.row.email }}
          </template>
        </el-table-column>

        <el-table-column width="100px" align="center" show-overflow-tooltip label="권한">
          <template slot-scope="scope">
            {{ scope.row.role }}
          </template>
        </el-table-column>

        <el-table-column width="100px" align="center" show-overflow-tooltip label="등급">
          <template slot-scope="scope">
            {{ scope.row.level }}
          </template>
        </el-table-column>

        <el-table-column width="150px" align="center" show-overflow-tooltip label="가입일">
          <template slot-scope="scope">
            {{ setCreatTime(scope.row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column width="80px" align="center" label="수정">
          <template slot-scope="scope">
            <i class="fa fa-cog" @click="changeUserInfo(scope.row)"></i>
          </template>
        </el-table-column>

        <el-table-column width="80px" align="center" label="삭제">
          <template slot-scope="scope">
            <i class="fa fa-trash-o" @click="handleDelete([scope.row.id])"></i>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination :current-page="listQuery.offset" :page-sizes="[8,15,20,30,40,50]" :page-size="listQuery.limit"
          :total="listQuery.total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
      <!-- 添加用户 -->
      <el-dialog title="添加用户" :visible.sync="addpopup" width="400px" class="addpopup">
        <el-form :model="addUserform" ref="addUserform" :rules="rules" status-icon>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="addUserform.nickname"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserform.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserform.password" type="password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkpassword">
            <el-input v-model="addUserform.checkpassword" type="password" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closePopup('addUserform')">取 消</el-button>
          <el-button type="primary" @click="sendForm('addUserform')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改用户信息 -->
      <el-dialog title="修改用户信息" :visible.sync="changePopup" width="400px" class="changePopup">
        <el-form :model="changeUserForm" ref="changeUserForm" :rules="rules" status-icon>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="changeUserForm.nickname"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="changeUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="region">
            <el-select v-model="changeUserForm.role" placeholder="">
              <el-option label="admin" value="admin"></el-option>
              <el-option label="user" value="user"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="等级" prop="region">
            <el-select v-model="changeUserForm.level" placeholder="">
              <el-option label="0" value="0"></el-option>
              <el-option label="1" value="1"></el-option>
              <el-option label="2" value="2"></el-option>
              <el-option label="3" value="3"></el-option>
              <el-option label="4" value="4"></el-option>
              <el-option label="5" value="5"></el-option>
              <el-option label="6" value="6"></el-option>
              <el-option label="7" value="7"></el-option>
              <el-option label="8" value="8"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closePopup('changeUserForm')">取 消</el-button>
          <el-button type="primary" @click="sendChangeForm('changeUserForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    timestamp2date
  } from '@/utils'
  import {
    getUserlist,
    addUser,
    delUser,
    updUser
  } from '@/api/user'
  export default {
    name: 'user',
    data() {
      var validatePass = (rule, value, callback) => {
        let reg = /(?=.{6,17})(?=.*\d)(?=.*[a-z])[\x20-\x7f]*/i;
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!reg.test(value)) {
          callback(new Error('密码必须包含数字和英文,最少6位最多17位'));
        } else {
          if (this.addUserform.checkpassword !== '') {
            this.$refs.addUserform.validateField('checkpassword');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.addUserform.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validateNickname = (rule, value, callback) => {
        let reg = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
        if (value === '') {
          callback(new Error('请输入昵称'));
        } else if (reg.test(value)) {
          callback(new Error('不能包含特殊字符'));
        } else {
          callback();
        }
      }
      return {
        listQuery: {
          total: 0,
          limit: 8,
          offset: 1,
          type: 'email',
          keywords: '',
        },
        list: [],
        listLoading: true,
        checkAll: false,
        checked: [],
        unChecked: true,
        isIndeterminate: false,
        addpopup: false,
        oldUserData:{},
        addUserform: {
          nickname: '',
          email: '',
          password: '',
          checkpassword: '',
        },
        changePopup: false,
        changeUserForm: {
          id:'',
          nickname: '',
          email: '',
          role: '',
          level: '',
        },
        rules: {
          email: [{
              required: true,
              message: '请输入email',
              trigger: 'blur'
            },
            {
              type: 'email',
              required: true,
              message: '请输入正确的email',
              trigger: 'change'
            }
          ],
          password: [{
            required: true,
            validator: validatePass,
            trigger: 'blur'
          }],
          checkpassword: [{
            required: true,
            validator: validatePass2,
            trigger: 'blur'
          }],
          nickname: [{
            required: true,
            validator: validateNickname,
            trigger: 'blur'
          }]
        }
      }
    },
    watch: {
      list: function(Value, oldValue) {
        this.id = [];
        for (let i = 0; i < this.list.length; i++) {
          this.id.push(this.list[i].id);
        }
        this.isIndeterminate = this.checked.length > 0 && this.checked.length < this.list.length;
        this.checkAll = this.checked.length === this.list.length
      },
      checked: function(Value, oldValue) {
        if (Value.length > 0) {
          this.unChecked = false
        } else {
          this.unChecked = true
        }
      }
    },
    created() {
      this.getUserlist()
    },
    methods: {
      changeUserInfo(data) {
        this.changeUserForm = JSON.parse(JSON.stringify(data));
        this.oldData = data;
        this.changePopup = true
      },
      sendChangeForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.listLoading = true
            updUser(this.changeUserForm).then(response => {
              this.list.forEach((item,index)=>{
                if(item.id === this.changeUserForm.id){
                  this.list[index].nickname = this.changeUserForm.nickname;
                  this.list[index].email = this.changeUserForm.email;
                  this.list[index].role = this.changeUserForm.role;
                  this.list[index].level = this.changeUserForm.level;
                }
              })
              this.changePopup = false;
              this.listLoading = false;
            }).catch((error) => {
              this.listLoading = false;
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleCheckAllChange(val) {
        this.checked = val ? this.id : [];
        this.isIndeterminate = false;
      },
      handleCheckedChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.list.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.list.length;
      },
      setCreatTime(date) {
        return timestamp2date(date)
      },
      getUserlist() {
        this.listLoading = true;
        getUserlist(this.listQuery.limit, this.listQuery.offset,this.listQuery.type,this.listQuery.keywords).then(response => {
          this.list = response.data;
          this.listQuery.total = response.total;
          this.listLoading = false;
        })
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getUserlist()
      },
      handleCurrentChange(val) {
        this.listQuery.offset = val
        this.getUserlist()
      },
      closePopup(formName) {
        if(formName==='changeUserForm'){
          this.changePopup = false;
        }else{
          this.addpopup = false;
        }
      },
      sendForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addpopup = false
            this.listLoading = true
            addUser(this.addUserform).then(response => {
              this.getUserlist();
            }).catch((error) => {
              this.listLoading = false;
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleDelete(id) {
        this.$confirm('이 정보를 삭제하시겠습니까?', '팁스', {
          confirmButtonText: '예',
          cancelButtonText: '아니요',
          type: 'warning'
        }).then(() => {
          let data = {
            id: id
          }
          this.listLoading = true;
          delUser(data).then(valid => {
            if (valid) {
              this.$message({
                type: 'success',
                message: '삭제되엿습니다'
              });
              this.getUserlist()
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '취소되엿습니다'
          });
        });
      }
    }
  }
</script>


<style rel="stylesheet/scss" lang="scss">
  .el-select .el-input {
    width: 100px;
  }

  .el-dialog {
    border-radius: 10px;

    .el-dialog__body {
      padding: 12px 20px;
    }

    .el-form-item__label {
      width: 80px;
    }

    .el-form-item__content {
      margin-left: 80px;
    }

    .el-select .el-input {
      width: 280px;
    }

  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .container {
    margin: 30px;

    .search {
      width: 500px;
      float: left;
    }

    .button-group {
      float: right;

    }

    .title:after {
      content: '';
      display: table;
      clear: both;
    }

    .user-avatar {
      width: 50px;
      height: 50px;
    }

    .pagination-container {
      padding: 15px;
    }

    .forwarding-set {
      padding: 0px !important;

      .artivle-batch-bar {
        width: 100%;
        background: #fff;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
        transition: 0.5s ease;
        position: relative;
        height: 50px;

        .el-checkbox {
          position: absolute;
          bottom: -32px;
          left: 17px;
        }

        .el-button {
          margin: 10px 15px;
        }

        .el-button i {
          padding-right: 4px;
        }
      }

      .artivle-batch-bar.hide {
        height: 0;
      }

      .title {
        margin-bottom: 15px;

        span {
          font-size: 14px;
          color: #404a54;
          line-height: 50px;
          font-weight: 500;
        }

        .button-group {
          button {
            cursor: pointer;
            background: #20a0ff;
            color: #fff;
            border: none;
            padding: 0px 20px;
            height: 40px;
            line-height: 40px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;

            i {
              padding-right: 5px;
            }
          }
        }
      }

      //按钮样式
      .bd {
        .name {
          color: #000;
          font-weight: 500;
        }

        .fa-trash-o,
        .fa-cog {
          color: #cbcbcb;
          cursor: pointer;
        }

        .fa-trash-o:hover,
        .fa-cog:hover {
          color: #404a54;
        }
      }

    }
  }
</style>
